package com.rla.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rla.common.constant.RegisterConstants;
import com.rla.common.core.page.TableDataInfo;
import com.rla.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rla.common.utils.StringUtils;
import com.rla.common.wechat.utils.RestTemplateUtil;
import com.rla.domain.MallOrderAfter;
import com.rla.domain.vo.MallOrderAfterVo;
import com.rla.mapper.MallOrderAfterMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.rla.domain.bo.MallOrderAddressBo;
import com.rla.domain.vo.MallOrderAddressVo;
import com.rla.domain.MallOrderAddress;
import com.rla.mapper.MallOrderAddressMapper;
import com.rla.service.IMallOrderAddressService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 订单地址绑定Service业务层处理
 *
 * @author rla
 * @date 2025-08-18
 */
@RequiredArgsConstructor
@Service
public class MallOrderAddressServiceImpl implements IMallOrderAddressService {

    private final MallOrderAddressMapper baseMapper;

    private final RestTemplateUtil restTemplateUtil;

    private final MallOrderAfterMapper mallOrderAfterMapper;

    /**
     * 查询订单地址绑定
     */
    @Override
    public MallOrderAddressVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询订单地址绑定列表
     */
    @Override
    public TableDataInfo<MallOrderAddressVo> queryPageList(MallOrderAddressBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MallOrderAddress> lqw = buildQueryWrapper(bo);
        Page<MallOrderAddressVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询订单地址绑定列表
     */
    @Override
    public List<MallOrderAddressVo> queryList(MallOrderAddressBo bo) {
        LambdaQueryWrapper<MallOrderAddress> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MallOrderAddress> buildQueryWrapper(MallOrderAddressBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MallOrderAddress> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getOrderId()), MallOrderAddress::getOrderId, bo.getOrderId());
        lqw.eq(StringUtils.isNotBlank(bo.getDeliveryCode()), MallOrderAddress::getDeliveryCode, bo.getDeliveryCode());
        lqw.like(StringUtils.isNotBlank(bo.getDeliveryName()), MallOrderAddress::getDeliveryName, bo.getDeliveryName());
        lqw.eq(StringUtils.isNotBlank(bo.getDeliveryNo()), MallOrderAddress::getDeliveryNo, bo.getDeliveryNo());
        lqw.eq(bo.getDeliveryTime() != null, MallOrderAddress::getDeliveryTime, bo.getDeliveryTime());
        lqw.eq(StringUtils.isNotBlank(bo.getAcceptTime()), MallOrderAddress::getAcceptTime, bo.getAcceptTime());
        lqw.eq(StringUtils.isNotBlank(bo.getTimeSlot()), MallOrderAddress::getTimeSlot, bo.getTimeSlot());
        lqw.like(StringUtils.isNotBlank(bo.getReceiveUserName()), MallOrderAddress::getReceiveUserName, bo.getReceiveUserName());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiveUserPhone()), MallOrderAddress::getReceiveUserPhone, bo.getReceiveUserPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiveUserAddress()), MallOrderAddress::getReceiveUserAddress, bo.getReceiveUserAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiveProvince()), MallOrderAddress::getReceiveProvince, bo.getReceiveProvince());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiveCity()), MallOrderAddress::getReceiveCity, bo.getReceiveCity());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiveCounty()), MallOrderAddress::getReceiveCounty, bo.getReceiveCounty());
        lqw.eq(StringUtils.isNotBlank(bo.getIsFreeShipping()), MallOrderAddress::getIsFreeShipping, bo.getIsFreeShipping());
        lqw.eq(bo.getMallPostage() != null, MallOrderAddress::getMallPostage, bo.getMallPostage());
        return lqw;
    }

    /**
     * 新增订单地址绑定
     */
    @Override
    public Boolean insertByBo(MallOrderAddressBo bo) {
        MallOrderAddress add = BeanUtil.toBean(bo, MallOrderAddress.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改订单地址绑定
     */
    @Override
    public Boolean updateByBo(MallOrderAddressBo bo) {
        MallOrderAddress update = BeanUtil.toBean(bo, MallOrderAddress.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public Boolean updateByOrderId(MallOrderAddressBo bo) {

        int update = baseMapper.update(null, Wrappers.lambdaUpdate(MallOrderAddress.class)
                .set(MallOrderAddress::getReceiveUserName, bo.getReceiveUserName())
                .set(MallOrderAddress::getReceiveUserPhone, bo.getReceiveUserPhone())
                .set(MallOrderAddress::getReceiveUserAddress, bo.getReceiveUserAddress())
                .set(MallOrderAddress::getReceiveProvince, bo.getReceiveProvince())
                .set(MallOrderAddress::getReceiveCity, bo.getReceiveCity())
                .set(MallOrderAddress::getReceiveCounty, bo.getReceiveCounty())
                .eq(MallOrderAddress::getOrderId, bo.getOrderId()));
        return update>0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MallOrderAddress entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除订单地址绑定
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    @Override
    public MallOrderAddressVo queryByOrderId(String orderId) {

        LambdaQueryWrapper< MallOrderAddress> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq( MallOrderAddress::getOrderId, orderId);
        MallOrderAddressVo vo = baseMapper.selectVoOne(queryWrapper);

        LambdaQueryWrapper<MallOrderAfter> lqw = Wrappers.lambdaQuery();
        lqw.eq(MallOrderAfter::getOrderId, orderId);
        MallOrderAfterVo afterVo = mallOrderAfterMapper.selectVoOne(lqw);
        if (ObjectUtil.isNotEmpty(afterVo)) {
            vo.setMallOrderAfterVo(afterVo);
        }
        return vo;
    }

    public MallOrderAddressVo queryByOrderId1(String orderId) {
        QueryWrapper<MallOrderAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        MallOrderAddressVo vo = baseMapper.selectVoOne(queryWrapper);
        return vo;
    }


    @Async
    @Override
    public JSONObject SMQJ(String orderId) {
        MallOrderAddressVo byOrderId = this.queryByOrderId1(orderId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("RequestType", 1801);
        map.put("OrderCode", orderId);
        map.put("ShipperType", 3);
//        map.put("ShipperCode", byOrderId.getDeliveryCode());
        map.put("ShipperCode", "");
        map.put("ProvinceName", byOrderId.getReturnProvince());
        map.put("CityName", byOrderId.getReturnCity());
        map.put("ExpAreaName", byOrderId.getReturnCounty());
        map.put("Address", byOrderId.getRefundUserAddress());
        map.put("Name", byOrderId.getRefundUserName());
        map.put("Mobile", byOrderId.getRefundUserPhone());
        map.put("StartDate", byOrderId.getStartTime());
        map.put("EndDate", byOrderId.getEndTime());
        String data = restTemplateUtil.postMapData(RegisterConstants.SMQJ, map);
        JSONObject jsonObject = JSON.parseObject(data);
        return jsonObject.getJSONObject("Message");
    }

    @Async
    @Override
    public JSONObject SMQJ1(MallOrderAddress orderAddress) {
//        MallOrderAddressVo byOrderId = this.queryByOrderId1(orderId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("RequestType", 1801);
        map.put("OrderCode", orderAddress.getOrderId());
        map.put("ShipperType", 3);
//        map.put("ShipperCode", byOrderId.getDeliveryCode());
        map.put("ShipperCode", "");
        map.put("ProvinceName", orderAddress.getReturnProvince());
        map.put("CityName", orderAddress.getReturnCity());
        map.put("ExpAreaName", orderAddress.getReturnCounty());
        map.put("Address", orderAddress.getRefundUserAddress());
        map.put("Name", orderAddress.getRefundUserName());
        map.put("Mobile", orderAddress.getRefundUserPhone());
        map.put("StartDate", orderAddress.getStartTime());
        map.put("EndDate", orderAddress.getEndTime());
        String data = restTemplateUtil.postMapData(RegisterConstants.SMQJ, map);
        JSONObject jsonObject = JSON.parseObject(data);
        return jsonObject.getJSONObject("Message");
    }

    @Override
    public JSONObject cancel(String orderId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("RequestType", 1802);
        map.put("OrderCode", orderId);
        String data = restTemplateUtil.postMapData(RegisterConstants.SMQJ, map);
        JSONObject jsonObject = JSON.parseObject(data);
        return jsonObject.getJSONObject("Message");
    }
}
